﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
// Copyright (C) 2021 kingerrobot
// 版权所有。 
//
// 文件名：BWcsLocSku
// 文件功能描述：
//
// 创建者：名字 (zzl)
// 时间：2021/12/9 15:13:54
//
// 修改人：
// 时间：
// 修改说明：
// 版本：V1.0.0
//----------------------------------------------------------------*/
#endregion
using K8.CBB;
using KingerRobot.MexicoSailunMDC.Dao;
using System.Data.Common;

namespace KingerRobot.MexicoSailunMDC.SpiService;

internal class BWcsManualCuringRecord : IWcsManualCuringRecord
{
    public int AddManualCuringRecordByProductCode(string curingModelCode, string productCode, DateTime? mesPutTime)
    {
        var result = 0;
        var db = Db.Default;

        var equipCuring = db.RcsEquipCurings.Where(t => t.CuringModeCode == curingModelCode).FirstOrDefault();
        var curingCode = equipCuring?.CuringCode;
        var curingLoc = equipCuring?.LocId ?? 0;
        var ems1 = equipCuring?.EmsId ?? 0;
        var ems2 = equipCuring?.EmsId2 ?? 0;

        var locName = db.RcsLocations.Where(t => t.Id == curingLoc).FirstOrDefault()?.LocName;

        var materialCode = db.MesProducts.Where(t => t.BcdNo == productCode).FirstOrDefault()?.MaterialCode;

        var curingRequest = db.MesCuringRequestMaterials.Where(t => t.CuringLocId == curingLoc).FirstOrDefault();

        var isEnableRequest = curingRequest?.IsEnableRequest ?? 0;
        var equipStatusMes = curingRequest?.EquipStatusMes ?? 0;

        var equipStatusHost = curingRequest?.EquipStatusHost ?? 0;
        var hostWmsFlag = curingRequest?.HostWmsFlag ?? 0;
        var maxCacheCount = curingRequest.MaxCacheCount;
        var realCacheCount = curingRequest.RealCacheCount;




        //查询设备状态
        List<ManualCuringEquip> equipList = new List<ManualCuringEquip>();
        var dbHelper = new DbHelper();
        var crnsql = @$"select re.equip_name as EquipName,re.equip_enable as EquipEnable,wee.err_code  as ErrCode ,wee.err_msg as ErrMsg ,re.objid as  EquipId,re.equip_type as EquipType
        from rcs_equip re left join wms_equip_err wee
        on re.objid=wee.equip_id
        AND wee.end_time IS NULL AND wee.err_msg IS NOT NULL 
        where re.equip_type in(3,10)";

        dbHelper.CommandText = crnsql;
        dbHelper.CommandType = System.Data.CommandType.Text;
        var data = dbHelper.GetXDataTable();
        

        if (data is not null && data.DataTable.Rows.Count > 0)
        {
            for (int i = 0; i < data.DataTable.Rows.Count; i++)
            {
                ManualCuringEquip equip =data.DataTable.Rows[i].Map<ManualCuringEquip>();
                equipList.Add(equip);
            }
        }
        //查订单(库存在订单表里)
        var orderData = db.WmsOutOrderSummarys.Where(t => t.TargetLoc == curingLoc).FirstOrDefault();

        var currentLoc = "";
        DateTime? taskTime = null;
        var taskId = orderData?.TaskId ?? 0;
        if (taskId > 0)
        {

            var task = db.WcsTasks.Join(db.WcsTaskCmds, f => f.Id, s => s.TaskId, (f, s) => new
            {
                f.CreateTime,
                s.CurrentLoc,
                s.TaskId,
            }).Join(db.RcsLocations, f => f.CurrentLoc, s => s.Id, (f, s) => new
            {
                f.CreateTime,
                s.LocName,
                f.TaskId,
            }).Where(t => t.TaskId == taskId).FirstOrDefault();
            currentLoc = task?.LocName;
            taskTime = task?.CreateTime;
        }



        //整合数据 
        //查找系统禁用堆垛机
        var disableCrn = equipList.Where(t => t.EquipType == 3 && t.EquipEnable == 0).ToList();
        var strDisableCrn = "";
        foreach (var item in disableCrn)
        {
            strDisableCrn += $"{item.EquipName}:禁用，";
        }
        //查找异常状态堆垛机
        var errorCrn = equipList.Where(t => t.EquipType == 3 && !string.IsNullOrWhiteSpace(t.ErrCode)).ToList();
        var strErrCrn = "";
        foreach (var item in errorCrn)
        {
            strErrCrn += $"{item.EquipName}-{item.ErrMsg},";
        }

        //查找异常状态ems
        var errorEms = equipList.Where(t => (t.EquipId == ems1 || t.EquipId == ems2) && !string.IsNullOrWhiteSpace(t.ErrCode)).ToList();
        var strErrEms = "";
        foreach (var item in errorEms)
        {
            strErrEms += $"{item.EquipName}-{item.ErrMsg},";
        }

        var manualCuringRecord = new POWcsManualCuringRecord()
        {
            Id = XID.Nextval,
            CrnError = strErrCrn,
            CrnDisable = strDisableCrn,
            CuringCode = curingCode,
            EmsStatus = strErrEms,
            LocId = curingLoc,
            LocName = locName,
            Stock = orderData?.Stock ?? 0,
            SummaryId = orderData?.Id,
            TaskId = taskId,
            MesPutTime = mesPutTime,
            ProductCode = productCode,
            MaterialCode = materialCode,
            IsEnableRequest = isEnableRequest,
            EquipStatusMes = equipStatusMes,
            OrderRemark = orderData?.RemarkMemo,
            TaskTime = taskTime,
            CurrentLoc = currentLoc,
            MaxCacheCount = maxCacheCount,
            RealCacheCount = realCacheCount,
            EquipStatusHost = equipStatusHost,
            HostWmsFlag = hostWmsFlag,
        };
        result = db.WcsManualCuringRecords.Insert(manualCuringRecord);

        return result;

    }

    public POWcsManualCuringRecord GetFirstManualCuringRecordDesc()
    {
        var db = Db.Default;
        var result = db.WcsManualCuringRecords.OrderByDescending(t => t.MesPutTime).FirstOrDefault();
        return result;
    }


}
